package com.dating.core.entries;

import java.util.Iterator;
import java.util.Map;

import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.util.NutMap;

public class Result {
	private NutMap data = new NutMap();

	private OperationState operationState = OperationState.DEFAULT;
	private String title;

	public static Result exception() {
		return me().setOperationState(OperationState.EXCEPTION);
	}

	public static Result unlogin() {
		return me().setOperationState(OperationState.UNLOGINED);
	}

	public static Result exception(Exception e) {
		return exception(e.getMessage());
	}

	public static Result exception(String msg) {
		return exception().addData("reason", msg);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Result fail(String reason) {
		Map data = new NutMap();
		data.put("reason", reason);
		return me().setOperationState(OperationState.FAIL).setData(data);
	}

	public static Result me() {
		return new Result();
	}

	public static Result success() {
		return me().setOperationState(OperationState.SUCCESS);
	}

	@SuppressWarnings("rawtypes")
	public static Result success(Map data) {
		return success().setData(data);
	}

	public Result() {
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Result(OperationState operationState, Map data, String title) {
		this.operationState = operationState;
		this.data = NutMap.WRAP(data);
		this.title = title;
	}

	@SuppressWarnings("rawtypes")
	public Result addData(Map data) {
		Iterator iterator = data.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next().toString();
			this.data.put(key, data.get(key));
		}
		return this;
	}

	public Result addData(String key, Object object) {
		if (this.data == null) {
			this.data = new NutMap();
		}
		this.data.put(key, object);
		return this;
	}

	public Result clear() {
		this.operationState = OperationState.DEFAULT;
		if (this.data != null) {
			this.data.clear();
		}
		this.title = "";
		return this;
	}

	public NutMap getData() {
		return this.data;
	}

	public NutMap getNutMapData() {
		return NutMap.WRAP(this.data);
	}

	public OperationState getOperationState() {
		return this.operationState;
	}

	public String getReason() {
		return getData().getString("reason");
	}

	public String getTitle() {
		return this.title;
	}

	public boolean isSuccess() {
		return (getOperationState() == OperationState.SUCCESS);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Result setData(Map data) {
		this.data = NutMap.WRAP(data);
		return this;
	}

	public Result setOperationState(OperationState operationState) {
		this.operationState = operationState;
		return this;
	}

	public Result setTitle(String title) {
		this.title = title;
		return this;
	}

	public String toString() {
		return Json.toJson(this, JsonFormat.forLook());
	}
}
